<script lang="ts" setup>
import dayjs from 'dayjs'
import {
  getCdnGroupListApi,
  getCdnNodeSimpleApi,
  getCdnStatisticsWafOverviewApi,
} from '@/apis/modules/cdn'

// import ContainerContent from '@/components/ContentContainer.vue'
import useTableColumn from './column'

import SecureLineChart from './components/SecureLineChart.vue'

const { staCodeNumberFormat } = useTableColumn()

const router = useRouter()
const selectRadio = ref<string | undefined>('today')
const chartType = ref('custom')
const typeList: { label: string, key: string }[] = [
  { label: '自定义规则', key: 'custom' },
  { label: '速率限制', key: 'rate' },
]

const loading = ref(false)
const queryData = reactive({
  group_id: '',
  node_ids: [],
})

const timeDate = ref(dayjs().format('YYYY-MM-DD'))

/** 时间变化 */
const daysMap = {
  today: dayjs().format('YYYY-MM-DD'),
  yesterday: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
}

// 跳转日志明细
function openLog(module: string) {
  localStorage.setItem('safeModule', module)
  router.push({
    name: 'LogDetails',
  })
}

function changeRadio(val: 'today' | 'yesterday') {
  if (val === 'today') {
    timeDate.value = daysMap.today
  }
  if (val === 'yesterday') {
    timeDate.value = daysMap.yesterday
  }
}
function handleDateRangePickerChange(val: string) {
  selectRadio.value = undefined
  const day = dayjs(val).format('YYYY-MM-DD')
  if (day === daysMap.today) {
    selectRadio.value = 'today'
  }
  if (day === daysMap.yesterday) {
    selectRadio.value = 'yesterday'
  }
}

// 站点数据总量数据
const siteOverviewData = ref<any>({})
const MathRandom = ref(0)
const NodeIdList = ref<any>([])
// 获取数据总量
function getSiteSummary() {
  loading.value = true
  getCdnStatisticsWafOverviewApi({
    data: {
      start_time: dayjs(timeDate.value).unix(),
      end_time: dayjs(timeDate.value).unix() + 86399,
      module: 0,
      group_id: queryData.group_id ? queryData.group_id : 0,
      node_ids: queryData.node_ids,
      //  node_ids:
      // queryData.node_ids.length > 0 ? queryData.node_ids : NodeIdList.value,
    },
  })
    .then((res) => {
      siteOverviewData.value = res.map
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
  MathRandom.value = Math.random() * 1
}
const regionList = ref<any>([])
const NodeList = ref<any>([])

// 获取集群
function getRegions() {
  getCdnGroupListApi({}).then((res) => {
    regionList.value = res.list
  })
}

// 获取节点
function changeRegion() {
  getCdnNodeSimpleApi({
    group_id: queryData.group_id,
  }).then((res) => {
    NodeList.value = res.list || []
    queryData.node_ids = []
    NodeIdList.value = Array.from(NodeList.value || []).map((item) => {
      return item?.id
    })
    getSiteSummary()
  })
}

// 站点下拉关闭时查询
function changeSite(open: boolean) {
  if (!open) {
    getSiteSummary()
  }
}

onMounted(() => {
  getRegions()
  changeRegion()
})

function disabledDate(current) {
  if (current && current > dayjs().endOf('day')) {
    return true
  }
  // 禁用30天之前的日期
  if (current && current < dayjs().subtract(30, 'day').startOf('day')) {
    return true
  }
  return false
}

watch(
  () => timeDate.value,
  (val) => {
    if (val)
      getSiteSummary()
  },
)

// 刷新
function refreshData() {
  getSiteSummary()
}
</script>

<template>
  <main-container :pagination="false">
    <div class="node-safe-view w-full">
      <div class="mb-4">
        <div class="w-full flex items-center justify-between">
          <a-radio-group
            v-model="selectRadio"
            type="button"
            class="h-8"
            @change="changeRadio"
          >
            <a-radio value="today">
              今日
            </a-radio>
            <a-radio value="yesterday">
              昨日
            </a-radio>
          </a-radio-group>
          <a-date-picker
            v-model="timeDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px; height: 32px"
            :allow-clear="false"
            :disabled-date="disabledDate"
            :show-now-btn="false"
            class="ml-4"
            @change="handleDateRangePickerChange"
          />
          <a-select
            v-model="queryData.group_id"
            :style="{ width: '220px', height: '32px' }"
            placeholder="请选择分组"
            class="ml-4"
            @change="changeRegion"
          >
            <a-option value="">
              全部分组
            </a-option>
            <a-option
              v-for="item in regionList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-option>
          </a-select>

          <a-select
            v-model="queryData.node_ids"
            :style="{ width: '220px', height: '30px' }"
            placeholder="全部节点      "
            allow-clear
            multiple
            :max-tag-count="1"
            class="site_select ml-4"
            @popup-visible-change="changeSite"
            @clear="getSiteSummary"
            @remove="getSiteSummary"
          >
            <a-option
              v-for="item in NodeList"
              :key="item.id"
              class="h-[28px]"
              :value="item.id"
            >
              {{ item.name }}
            </a-option>
          </a-select>
          <div class="flex-1" />
          <a-button
            class="ml-auto shrink-0 text-color-1"
            type="outline"
            :disabled="loading"
            @click="refreshData"
          >
            <template #icon>
              <i-icons-refresh :class="{ 'animate-spin': loading }" />
            </template>
          </a-button>

          <!-- <a-button class="mr-[-16px] shrink-0 h-[30px]! w-[30px]!" @click="refreshData()">
            <template #icon>
              <i-icons-refresh size="4" :spin="loading" />
            </template>
          </a-button> -->

          <!-- <CloudFilterBar
          v-model="params"
          class="flex-1 ml-4"
          :run="run"
          :schemes="filterSchemes"></CloudFilterBar> -->
        </div>
      </div>
      <div class="item-content">
        <div
          class="item-content-card card-bg-green"
          @click="openLog('1')"
        >
          <div class="item-content-card-title">
            自定义规则 ({{
              staCodeNumberFormat(siteOverviewData[1]?.total || 0).unit
            }})
          </div>
          <div class="item-content-card-val">
            {{ staCodeNumberFormat(siteOverviewData[1]?.total || 0).value }}
          </div>
          <a-divider
            :size="1"
            type="dashed"
            :margin="24"
          />
          <div class="item-content-card-sub">
            <div class="item-content-icon">
              <div class="item-content-icon-img">
                <i-icons-prevent />
              </div>
              <div class="item-content-icon-text">
                阻止
                {{
                  staCodeNumberFormat(siteOverviewData[1]?.block_cnt || 0).value
                }}
                {{
                  staCodeNumberFormat(siteOverviewData[1]?.block_cnt || 0).unit
                }}
              </div>
            </div>
            <div class="item-content-icon">
              <div class="item-content-icon-img">
                <i-icons-observe />
              </div>
              <div class="item-content-icon-text">
                观察
                {{
                  staCodeNumberFormat(siteOverviewData[1]?.log_cnt || 0).value
                }}
                {{
                  staCodeNumberFormat(siteOverviewData[1]?.log_cnt || 0).unit
                }}
              </div>
            </div>
          </div>
        </div>
        <div
          class="item-content-card card-bg-blue"
          @click="openLog('2')"
        >
          <div class="item-content-card-title">
            速率限制 ({{
              staCodeNumberFormat(siteOverviewData[2]?.total || 0).unit
            }})
          </div>
          <div class="item-content-card-val">
            {{ staCodeNumberFormat(siteOverviewData[2]?.total || 0).value }}
          </div>

          <a-divider
            :size="1"
            type="dashed"
            :margin="24"
          />
          <div class="item-content-card-sub">
            <div class="item-content-icon">
              <div class="item-content-icon-img">
                <i-icons-prevent />
              </div>
              <div class="item-content-icon-text">
                阻止
                {{
                  staCodeNumberFormat(siteOverviewData[2]?.block_cnt || 0).value
                }}
                {{
                  staCodeNumberFormat(siteOverviewData[2]?.block_cnt || 0).unit
                }}
              </div>
            </div>
            <div class="item-content-icon">
              <div class="item-content-icon-img">
                <i-icons-observe />
              </div>
              <div class="item-content-icon-text">
                观察
                {{
                  staCodeNumberFormat(siteOverviewData[2]?.log_cnt || 0).value
                }}
                {{
                  staCodeNumberFormat(siteOverviewData[2]?.log_cnt || 0).unit
                }}
              </div>
            </div>
          </div>
        </div>
        <div class="item-content-card-null" />
      </div>
      <div>
        <div class="overview-chart__header">
          <a-radio-group
            v-model="chartType"
            style="position: relative; top: 30px; z-index: 10"
            type="button"
          >
            <a-radio
              v-for="{ key, label } in typeList"
              :key="key"
              :value="key"
              :name="key"
            >
              {{ label }}
            </a-radio>
          </a-radio-group>
        </div>
        <secure-line-chart
          :type="chartType"
          :time-date="timeDate"
          height="500px"
          :params="queryData"
          :site-id="NodeIdList"
          :math-random="MathRandom"
        />
      </div>
    </div>
  </main-container>
</template>

<style lang="less" scoped>
.node-safe-view {
  .item-content {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    align-self: stretch;

    .item-content-card {
      display: flex;
      padding: 24px;
      flex-direction: column;
      align-items: flex-start;
      //gap: 24px;
      flex: 1 0 0;

      &.card-bg-green {
        border-radius: var(--border-radius-xl, 12px);
        border: 1px solid var(--border-1, #f2f3f5);
        background: linear-gradient(180deg, #f3faf3 0%, #fff 100%);
      }

      &.card-bg-blue {
        border-radius: var(--border-radius-xl, 12px);
        border: 1px solid var(--border-1, #f2f3f5);
        background: linear-gradient(180deg, #f0f6ff 0%, #fff 100%);
      }

      // &:hover {
      //   border-radius: 4px;
      //   border: 1px solid var(---color-border-white, #fff);
      //   box-shadow: 0px 4px 24px 0px rgba(209, 222, 229, 0.3);
      //   cursor: pointer;
      // }

      .item-content-card-title {
        color: var(--text-1, #1d2129);

        /* regular/14 */
        font-family: 'Microsoft YaHei UI';
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: 20px;
        /* 142.857% */
      }

      .item-content-card-val {
        // color: var(---color-text-2, #393c40);
        // font-family: 'BebasNeue';
        // font-size: 24px;
        // font-style: normal;
        // font-weight: 400;
        // line-height: normal;
        margin-top: 8px;
        color: var(--text-1, #1d2129);

        /* bold/20 */
        font-family: 'Microsoft YaHei UI';
        font-size: 20px;
        font-style: normal;
        font-weight: 700;
        line-height: normal;
      }

      .item-content-card-sub {
        display: flex;
        align-items: flex-start;
        gap: 24px;
        align-self: stretch;

        .item-content-icon {
          display: flex;
          align-items: center;
          gap: 4px;

          .item-content-icon-img {
            display: flex;
            align-items: center;
            gap: 4px;
          }

          .item-content-icon-text {
            display: flex;
            align-items: center;
            gap: 4px;
            color: var(--text-2, #4e5969);

            /* regular/12 */
            font-family: 'Microsoft YaHei UI';
            font-size: 12px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
          }
        }
      }
    }

    .item-content-card-null {
      display: flex;
      padding: 16px 24px;
      width: 33%;
    }
  }

  :deep(.site_select) {
    height: 32px !important;
    background-color: #fff;

    .arco-select-view-inner {
      white-space: nowrap;
      padding-top: 0px !important;

      .arco-tag {
        white-space: nowrap;
      }

      .arco-select-view-input {
        width: 64px !important;
      }

      .arco-select-view-input::placeholder {
        color: #86909c;
        font-size: 12px;
      }
    }
  }
}

:deep(.arco-radio-group-button) {
  border-radius: var(--border-radius-lg, 8px);
  .arco-radio-button {
    border-radius: var(--border-radius-lg, 6px);
  }
}
</style>
